package zhibi.learn.rabbitmq.client;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author 执笔
 * @date 2021/2/22 17:48
 */
public class MqUtils {

    /**
     * 连接mq
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnect() throws Exception {
        // 连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 格式  amqp://用户名:密码@host:port/vhost
        factory.setUri("amqp://admin:admin@127.0.0.1:5672/my_vhost");
        // 创建连接
        return factory.newConnection();
    }

    /**
     * 新建信道
     *
     * @return
     */
    public static Channel createChannel() throws Exception {
        return getConnect().createChannel();
    }


    /**
     * 绑定队列
     *
     * @param channel
     * @param exchangeName
     * @param queueName
     * @param routingKey
     */
    public static void queueBind(Channel channel, String exchangeName, String queueName, String routingKey) throws Exception {
        channel.exchangeDeclare(exchangeName, "topic", true, false, false, null);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
    }
}
